//
//  FYUserPage.m
//  ThePainter
//
//  Created by Sean on 15/9/11.
//  Copyright (c) 2015年 FeiYu. All rights reserved.
//

#import "FYUserPage.h"
#import "FYUtils.h"
#import "FYUserPageCell.h"
#import "MJRefresh.h"
#import "FYUserViewModel.h"
#import "FYUserPageModel.h"
#import "FYPictureUtil.h"
#import "FYFirstListModel.h"
#import "FYProductDetailPage.h"

static NSString *CellIdentifier = @"FYCollectionCell";
static CGFloat BackGroupHeight = 300;

@interface FYUserPage ()

@property (nonatomic, strong) UICollectionView *clView;
@property (nonatomic, copy) NSString *userId;
@property (nonatomic, strong) FYUserViewModel *viewModel;
@property (nonatomic, strong) FYUserPageModel *model;
@property (nonatomic, strong) UIImageView *imgTop;
@property (nonatomic, strong) UIImageView *imgAvatar;
@property (nonatomic, strong) FYLabel *labUsername;

- (void)initView;

@end

@implementation FYUserPage

- (instancetype)initWithUserId:(NSString*)userId {
    if (self = [super init]) {
        self.userId = userId;
        self.viewModel = [[FYUserViewModel alloc] init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initView];
    [self initRefreshFoot];
    [self loadNewData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initView {
    
    //更改push出来的页面的返回按钮标题
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    self.clView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:layout];
    self.clView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.clView];
    [self.clView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.view.mas_bottom);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
    }];
    
    [self.clView registerClass:[FYUserPageCell class] forCellWithReuseIdentifier:CellIdentifier];
    
    self.clView.delegate = self;
    self.clView.dataSource = self;
    
    //顶部背景
    self.clView.contentInset = UIEdgeInsetsMake(BackGroupHeight, 0, 0, 0);
    self.imgTop = [[UIImageView alloc] initWithFrame:CGRectMake(0, -BackGroupHeight, [FYUtils fyScreenWidth], BackGroupHeight)];
    self.imgTop.image = [FYPictureUtil clipImage:[UIImage imageNamed:@"imgTop"] withSize:CGSizeMake([FYUtils fyScreenWidth], BackGroupHeight)];
    [self.clView addSubview:self.imgTop];
    
    //顶部容器
    UIView *topContainer = [[UIView alloc] initWithFrame:CGRectMake(0, -BackGroupHeight, [FYUtils fyScreenWidth], BackGroupHeight)];
    topContainer.backgroundColor = [UIColor clearColor];
    [self.clView addSubview:topContainer];
    
    //头像
    CGFloat aW = CGRectGetWidth(topContainer.frame) / 100 * 20;
    CGFloat aH = aW;
    CGFloat aX = CGRectGetWidth(topContainer.frame) / 2;
    CGFloat aY = CGRectGetHeight(topContainer.frame) / 100 * 30;
    self.imgAvatar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, aW, aH)];
    self.imgAvatar.center = CGPointMake(aX, aY);
    self.imgAvatar.layer.cornerRadius = aW / 2;
    self.imgAvatar.backgroundColor = [UIColor clearColor];
    self.imgAvatar.layer.masksToBounds = YES;
    [topContainer addSubview:self.imgAvatar];
    
    //名字
    self.labUsername = [[FYLabel alloc] initWithString:@"" size:fyLabSize4 color:[UIColor whiteColor]];
    CGFloat uX = CGRectGetWidth(topContainer.frame) / 2;
    CGFloat uY = CGRectGetHeight(topContainer.frame) / 100 * 50;
    self.labUsername.center = CGPointMake(uX, uY);
    [topContainer addSubview:self.labUsername];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat yOffset  = scrollView.contentOffset.y;
    CGFloat xOffset = (yOffset + BackGroupHeight) / 2;
    if (yOffset < -BackGroupHeight) {
        
        CGRect rect = self.imgTop.frame;
        rect.origin.y = yOffset;
        rect.origin.x = xOffset;
        
        CGFloat scale = BackGroupHeight / [FYUtils fyScreenWidth];
        rect.size.width = [FYUtils fyScreenWidth] + fabs(xOffset) * 2;
        rect.size.height = rect.size.width * scale;
        
        self.imgTop.frame = rect;
    }
    
    CGFloat alpha = (yOffset + BackGroupHeight) / BackGroupHeight;
    [self.navigationController.navigationBar setBackgroundImage:[FYUtils fyImageWithColor:[[UIColor whiteColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];

    self.navigationController.navigationBar.tintColor = [UIColor colorWithHue:1 - alpha saturation:1 - alpha brightness:1 - alpha alpha:1];
    
//    alpha = fabs(alpha);
//    alpha = fabs(1 - alpha);
//    
//    alpha = alpha < 0.2 ? 0 : alpha - 0.2;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.model.products.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    FYUserPageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    if (!cell.isLoadModel) {
        [cell loadModel:self.model.products[indexPath.row]];
    }
    return cell;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat sw = [FYUtils fyScreenWidth];
    CGFloat w = sw / 2 - 10;
    CGFloat h = w / 100 * 125;
    return CGSizeMake(w, h);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(10, 5, 0, 5);
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    //跳转到详情页面
    FYProduct *product = self.model.products[indexPath.row];
    FYProductDetailPage *page = [[FYProductDetailPage alloc] initWithProductId:product.productId];
    [self.navigationController pushViewController:page animated:YES];
}

- (void)initRefreshFoot {
    
    NSArray *refreshingImages = @[[UIImage imageNamed:@"loading_1"],
                                  [UIImage imageNamed:@"loading_2"], 
                                  [UIImage imageNamed:@"loading_3"],
                                  [UIImage imageNamed:@"loading_4"]];
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    // 设置刷新图片
    [footer setImages:refreshingImages forState:MJRefreshStateRefreshing];
    // 设置尾部
    self.clView.footer = footer;
}

- (void)loadNewData {
    
    [self.viewModel loadNewData:self.userId valueBlock:^(id returnValue) {
        self.model = returnValue;
        [self.clView reloadData];
        [self finishLoadNewData];
        [self refreshView];
    } errorBlock:^(id errorCode) {
        [self finishLoadNewData];
    } failureBlock:^{
        [self finishLoadNewData];
    }];
}

- (void)loadMoreData {
    
    [self.viewModel loadMoreData:self.model.products valueBlock:^(id returnValue) {
        self.model = returnValue;
        [self.clView reloadData];
        [self finishLoadMoreData];
    } errorBlock:^(id errorCode) {
        
    } failureBlock:^ {
        //提示没有更多数据
        [self noMoreData];
    }];
}

- (void)refreshView {
    [self.imgAvatar sd_setImageWithURL:[NSURL URLWithString:self.model.user.avatar]];
    [self.labUsername setStringAndCenter:self.model.user.username];
}

- (void)finishLoadNewData {
    [self.clView.header endRefreshing];
}

- (void)finishLoadMoreData {
    [self.clView.footer endRefreshing];
}

- (void)noMoreData {
    [self.clView.footer noticeNoMoreData];
}

- (void)resetNoMore {
    [self.clView.footer resetNoMoreData];
}

@end
